package com.zzyl.job;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.Constants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备上报数据报警规则过滤
 *
 * @author itcast
 **/
@Component
public class AlertJob {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AlertRuleMapper alertRuleMapper;
    
    @Autowired
    private AlertRuleService alertRuleService;

    /**
     * 设备上报数据报警规则过滤<br>
     * 周期：每分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void deviceDataAlertFilter() {
        //1.查询所有报警规则，如果为空，程序结束
        List<AlertRule> allAlertRules = alertRuleMapper.selectByFunctionId(null, null, null);
        if (CollUtil.isEmpty(allAlertRules)) {
            return;
        }

        //2.查询所有设备最新上报数据，如果为空，程序结束
        List<Object> jsonStrList = redisTemplate.opsForHash().values(CacheConstants.DEVICE_LASTDATA_CACHE_KEY);
        if (CollUtil.isEmpty(jsonStrList)) {
            return;
        }

        //3.设备上报数据不为空，提取设备上报数据为list
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        jsonStrList.forEach(json -> deviceDataVoList.addAll(JSONUtil.toList(json.toString(), DeviceDataVo.class)));

        //4.对每一条设备上报数据进行报警规则校验
        deviceDataVoList.forEach(d -> alertRuleService.alertFilter(d));
    }
}